// 购物车数据
let cart = [];

// DOM元素加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // DOM元素
    const cartToggle = document.getElementById('cartToggle');
    const closeCart = document.getElementById('closeCart');
    const cartSidebar = document.getElementById('cartSidebar');
    const cartOverlay = document.getElementById('cartOverlay');
    const cartItems = document.getElementById('cartItems');
    const emptyCart = document.getElementById('emptyCart');
    const cartCount = document.getElementById('cartCount');
    const cartTotal = document.getElementById('cartTotal');
    const checkoutBtn = document.getElementById('checkoutBtn');
    const checkoutModal = document.getElementById('checkoutModal');
    const modalOverlay = document.getElementById('modalOverlay');
    const closeModal = document.getElementById('closeModal');
    const orderItems = document.getElementById('orderItems');
    const orderTotal = document.getElementById('orderTotal');
    const confirmOrder = document.getElementById('confirmOrder');
    const successModal = document.getElementById('successModal');
    const successOverlay = document.getElementById('successOverlay');
    const closeSuccessModal = document.getElementById('closeSuccessModal');
    const categoryBtns = document.querySelectorAll('.category-btn');
    const loadMoreBtn = document.getElementById('loadMore');
    const tableNumberInput = document.getElementById('tableNumber');
    const orderLoading = document.getElementById('orderLoading');
    const errorModal = document.getElementById('errorModal');
    const errorOverlay = document.getElementById('errorOverlay');
    const closeErrorModal = document.getElementById('closeErrorModal');
    const errorMessage = document.getElementById('errorMessage');
    const orderIdElement = document.getElementById('orderId');

    // 打开购物车
    cartToggle.addEventListener('click', () => {
        cartSidebar.classList.remove('translate-x-full');
        cartOverlay.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    });

    // 关闭购物车
    function closeCartSidebar() {
        cartSidebar.classList.add('translate-x-full');
        cartOverlay.classList.add('hidden');
        document.body.style.overflow = '';
    }

    closeCart.addEventListener('click', closeCartSidebar);
    cartOverlay.addEventListener('click', closeCartSidebar);

    // 打开结算弹窗
    checkoutBtn.addEventListener('click', () => {
        closeCartSidebar();
        updateOrderItems();
        checkoutModal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    });

    // 关闭结算弹窗
    function closeCheckoutModal() {
        checkoutModal.classList.add('hidden');
        document.body.style.overflow = '';
    }

    closeModal.addEventListener('click', closeCheckoutModal);
    modalOverlay.addEventListener('click', closeCheckoutModal);

    // 关闭成功弹窗
    function closeSuccess() {
        successModal.classList.add('hidden');
        document.body.style.overflow = '';
    }

    closeSuccessModal.addEventListener('click', () => {
        closeSuccess();
        // 清空购物车
        cart = [];
        updateCart();
    });

    successOverlay.addEventListener('click', closeSuccess);

    // 关闭错误弹窗
    function closeError() {
        errorModal.classList.add('hidden');
    }

    closeErrorModal.addEventListener('click', closeError);
    errorOverlay.addEventListener('click', closeError);

    // 确认订单并提交到后端
    confirmOrder.addEventListener('click', async () => {
        // 验证房间号
        const tableNumber = tableNumberInput.value.trim();
        if (!tableNumber) {
            alert('请输入房间号或桌号');
            tableNumberInput.focus();
            return;
        }

        // 显示加载状态
        confirmOrder.classList.add('hidden');
        orderLoading.classList.remove('hidden');

        try {
            // 准备订单数据
            const orderData = {
                table_number: tableNumber,
                items: cart.map(item => ({
                    id: item.id,
                    name: item.name,
                    price: item.price,
                    quantity: item.quantity
                })),
                total: cart.reduce((sum, item) => sum + (item.price * item.quantity), 0)
            };

            // 发送订单到后端
            const response = await fetch('/api/submit-order', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(orderData)
            });

            const result = await response.json();

            if (result.success) {
                // 订单提交成功
                closeCheckoutModal();
                orderIdElement.textContent = result.order_id;
                successModal.classList.remove('hidden');
            } else {
                // 订单提交失败
                errorMessage.textContent = result.message || '订单提交失败，请稍后重试';
                errorModal.classList.remove('hidden');
            }
        } catch (error) {
            console.error('Error submitting order:', error);
            errorMessage.textContent = '网络错误，无法提交订单，请稍后重试';
            errorModal.classList.remove('hidden');
        } finally {
            // 恢复按钮状态
            confirmOrder.classList.remove('hidden');
            orderLoading.classList.add('hidden');
        }
    });

    // 添加商品到购物车
    document.addEventListener('click', function(e) {
        if (e.target.closest('.add-to-cart')) {
            const btn = e.target.closest('.add-to-cart');
            const id = btn.dataset.id;
            const name = btn.dataset.name;
            const price = parseFloat(btn.dataset.price);
            const img = btn.dataset.img;

            // 检查商品是否已在购物车中
            const existingItem = cart.find(item => item.id === id);

            if (existingItem) {
                // 增加数量
                existingItem.quantity += 1;
            } else {
                // 添加新商品
                cart.push({
                    id,
                    name,
                    price,
                    img,
                    quantity: 1
                });
            }

            // 更新购物车
            updateCart();

            // 添加动画效果
            btn.classList.add('scale-in');
            setTimeout(() => {
                btn.classList.remove('scale-in');
            }, 200);
        }
    });

    // 更新购物车
    function updateCart() {
        // 更新购物车数量
        const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
        cartCount.textContent = totalItems;

        // 更新购物车内容
        cartItems.innerHTML = '';

        if (cart.length === 0) {
            // 购物车为空
            emptyCart.classList.remove('hidden');
            checkoutBtn.disabled = true;
            cartTotal.textContent = '¥0';
        } else {
            // 隐藏空购物车提示
            emptyCart.classList.add('hidden');
            checkoutBtn.disabled = false;

            // 计算总价
            let total = 0;

            // 添加购物车商品
            cart.forEach(item => {
                total += item.price * item.quantity;

                const cartItem = document.createElement('div');
                cartItem.className = 'flex items-center justify-between py-2 border-b border-neutral-100';
                cartItem.innerHTML = `
                    <div class="flex items-center">
                        <img src="${item.img}" alt="${item.name}" class="w-14 h-14 object-cover rounded-md mr-3">
                        <div>
                            <h4 class="font-medium text-neutral-800">${item.name}</h4>
                            <p class="text-primary font-medium">¥${item.price.toFixed(2)}</p>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <button class="decrease-qty w-6 h-6 flex items-center justify-center rounded-full border border-neutral-300 text-neutral-600 hover:bg-neutral-100 transition-colors" data-id="${item.id}">
                            <i class="fa fa-minus text-xs"></i>
                        </button>
                        <span class="mx-3 text-neutral-800">${item.quantity}</span>
                        <button class="increase-qty w-6 h-6 flex items-center justify-center rounded-full border border-neutral-300 text-neutral-600 hover:bg-neutral-100 transition-colors" data-id="${item.id}">
                            <i class="fa fa-plus text-xs"></i>
                        </button>
                    </div>
                `;
                cartItems.appendChild(cartItem);
            });

            // 更新总价
            cartTotal.textContent = `¥${total.toFixed(2)}`;

            // 添加数量增减事件监听
            document.querySelectorAll('.decrease-qty').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.dataset.id;
                    const item = cart.find(item => item.id === id);

                    if (item.quantity > 1) {
                        item.quantity -= 1;
                    } else {
                        // 从购物车中移除商品
                        cart = cart.filter(item => item.id !== id);
                    }

                    updateCart();
                });
            });

            document.querySelectorAll('.increase-qty').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.dataset.id;
                    const item = cart.find(item => item.id === id);
                    item.quantity += 1;
                    updateCart();
                });
            });
        }
    }

    // 更新订单项目
    function updateOrderItems() {
        orderItems.innerHTML = '';
        let total = 0;

        cart.forEach(item => {
            total += item.price * item.quantity;

            const orderItem = document.createElement('div');
            orderItem.className = 'flex justify-between items-center';
            orderItem.innerHTML = `
                <span class="text-neutral-800">${item.name} x ${item.quantity}</span>
                <span class="font-medium">¥${(item.price * item.quantity).toFixed(2)}</span>
            `;
            orderItems.appendChild(orderItem);
        });

        orderTotal.textContent = `¥${total.toFixed(2)}`;
    }

    // 分类按钮切换
    categoryBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除所有按钮的活跃状态
            categoryBtns.forEach(b => {
                b.classList.remove('bg-primary', 'text-white');
                b.classList.add('bg-white', 'text-neutral-700', 'shadow-sm');
            });

            // 设置当前按钮为活跃状态
            btn.classList.remove('bg-white', 'text-neutral-700', 'shadow-sm');
            btn.classList.add('bg-primary', 'text-white');

            // 这里可以添加分类筛选逻辑
        });
    });

    // 加载更多功能
    loadMoreBtn.addEventListener('click', () => {
        // 显示加载状态
        loadMoreBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 加载中...';
        loadMoreBtn.disabled = true;

        // 模拟加载延迟
        setTimeout(() => {
            // 克隆现有的菜品卡片并修改内容作为新菜品
            const foodCards = document.querySelectorAll('.food-card');
            const container = document.querySelector('.grid');

            foodCards.forEach((card, index) => {
                if (index < 3) { // 只克隆3个菜品
                    const clone = card.cloneNode(true);
                    const id = parseInt(card.querySelector('.add-to-cart').dataset.id) + 10 + index;
                    const img = `https://picsum.photos/seed/food${id}/400/300`;

                    // 修改克隆卡片的信息
                    clone.querySelector('img').src = img;
                    clone.querySelector('img').alt = `推荐菜品${id}`;
                    clone.querySelector('h3').textContent = `推荐菜品${id}`;
                    clone.querySelector('.add-to-cart').dataset.id = id;
                    clone.querySelector('.add-to-cart').dataset.name = `推荐菜品${id}`;
                    clone.querySelector('.add-to-cart').dataset.img = img;

                    container.appendChild(clone);
                }
            });

            // 恢复按钮状态
            loadMoreBtn.innerHTML = '加载更多 <i class="fa fa-angle-down ml-1"></i>';
            loadMoreBtn.disabled = false;
        }, 1500);
    });

    // 初始化购物车
    updateCart();
});
